#!/usr/bin/env python
# coding: utf-8

# # 1-张量

# TensorFlow框架主要任务皆关于定义张量和运行张量，张量是对矢量和矩阵向潜在的更高维度的泛化。TensorFlow 在内部将张量表示为基本数据类型的 n 维数组。张量中的每个元素都具有相同的数据类型，且该数据类型一定是已知的。形状，即张量的维数和每个维度的大小，可能只有部分已知。如果其输入的形状也完全已知，则大多数操作会生成形状完全已知的张量，但在某些情况下，只能在执行图时获得张量的形状。常用的张量有：
# - tf.constant
# - tf.placeholder
# - tf.Variable

# In[34]:


import numpy as np
import tensorflow as tf
print("Packages loaded")


# 打开会话

# In[35]:


sess = tf.Session()
print("Open Session")


# # 1.1-TF常量

# In[36]:


tf_ct = tf.constant("Tensorflow Constant")
print(tf_ct)


# In[37]:


out = sess.run(tf_ct)
print(type(out))
print(out)
print(out.decode("utf-8"))


# # 其他类型的常量

# In[38]:


a = tf.constant(1.5)
print(type(a))
print(a)


# In[39]:


a_out = sess.run(a)
print(type(a_out))
print(a_out)


# # 1.2-占位符(Placeholder)

# In[40]:


x = tf.placeholder(tf.float32, [None, 5])
print(x)


# # 1.3-变量(Variables)

# In[41]:


weight = tf.Variable(tf.random_normal([5, 2], stddev=0.1))
print(type(weight))
print(weight)


# In[42]:


init = tf.global_variables_initializer()
sess.run(init)
weight_out = sess.run(weight)
print(type(weight_out))
print(weight_out)


# # 1.4-张量阶数
# - 0	标量（只有大小）
# - 1	矢量（大小和方向）
# - 2	矩阵（数据表）
# - 3	3 阶张量（数据立体）
# - n	n 阶张量

# 0阶张量
# ```python
# mammal = tf.Variable("Elephant", tf.string)
# ignition = tf.Variable(451, tf.int16)
# floating = tf.Variable(3.14159265359, tf.float64)
# its_complicated = tf.Variable(12.3 - 4.85j, tf.complex64)
# ```

# 1阶张量
# ```python
# mystr = tf.Variable(["Hello"], tf.string)
# cool_numbers  = tf.Variable([3.14159, 2.71828], tf.float32)
# first_primes = tf.Variable([2, 3, 5, 7, 11], tf.int32)
# its_very_complicated = tf.Variable([12.3 - 4.85j, 7.5 - 6.23j], tf.complex64)
# ```

# 2阶张量
# ```python
# mymat = tf.Variable([[7],[11]], tf.int16)
# myxor = tf.Variable([[False, True],[True, False]], tf.bool)
# linear_squares = tf.Variable([[4], [9], [16], [25]], tf.int32)
# squarish_squares = tf.Variable([ [4, 9], [16, 25] ], tf.int32)
# mymatC = tf.Variable([[7],[11]], tf.int32)
# ```

# n=4阶张量
# ```python
# my_image = tf.zeros([10, 299, 299, 3])  # batch x height x width x color
# ```

# # 2-算子(Operators）

# In[43]:


b = tf.constant(1.5)
a_plus_b = tf.add(a, b)


# In[44]:


a_plus_b_out = sess.run(a_plus_b)
print(type(a_plus_b_out))
print(a_plus_b_out)


# In[45]:


a_mul_b = tf.multiply(a, b)
a_mul_b_out = sess.run(a_mul_b)
print(type(a_mul_b_out))
print(a_mul_b_out)


# ## 算子+占位符

# In[46]:


oper = tf.matmul(x, weight)
print(oper)


# In[47]:


data = np.random.rand(1, 5)
oper_out = sess.run(oper, feed_dict={x: data})
print(oper_out)


# In[48]:


data = np.random.rand(2, 5)
oper_out = sess.run(oper, feed_dict={x: data})
print(oper_out)
